// NodeJS libraries
fs = require('fs');
path = require('path');

// Globals
global.LIB = path.dirname(path.dirname(__dirname)) + '/src';

// Own libraries
compiler = require('./compiler');

if (require.extensions && !require.extensions['.bjs']) {
	require.extensions['.bjs'] = function(module, filename) {
		var script = compile(filename);
    	return module._compile(script);
    }
}

run = function(bjsFile) {
	var mainModule = require.main;
    mainModule.filename = fs.realpathSync(bjsFile);
    if(mainModule.moduleCache) mainModule.moduleCache = {};
    mainModule.paths = require('module')._nodeModulePaths(path.dirname(fs.realpathSync(bjsFile)));

	var script = compiler.compile(fs.readFileSync(bjsFile, 'utf8'));

    var tmpReturn = function() { return mainModule._compile(script, mainModule.filename) };
    fs.stat('compiled', function(err, stats) {
        if( err || stats.isDirectory() ) {
            fs.mkdir('compiled', function() {
                fs.writeFile("compiled/"+bjsFile+".compiled.js", script, 'utf-8', function() {
                    tmpReturn();
                });
            });
        } else {
            fs.writeFile("compiled/"+bjsFile+".compiled.js", script, 'utf-8', function() {
                tmpReturn();
            });
        }
    });
    
    // return mainModule._compile(script, mainModule.filename);
}

runSource = function(bjsSource) {
    var mainModule = require.main;
    if(mainModule.moduleCache) mainModule.moduleCache = {};

    var script = compiler.compile(bjsSource);

    return mainModule._compile(script, mainModule.filename);
}

exports.VERSION = '0.0.2';
exports.run = run;
exports.runSource = runSource;